<?php


namespace App\Http\Rest\Shop\Resource;

use App\Constants\Sex;
use App\Exceptions\BusinessException;
use App\Http\Entities\AccountEntity;
use App\Http\Entities\ArticleEntity;
use App\Http\Entities\ClientEntity;
use App\Http\Entities\MemberEntity;
use App\Http\Entities\SecretEntity;
use App\Http\Rest\Shop\BaseResource;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Request\ServerRequest;
use Framework\Foundation\Response\ResponseGen;
use think\facade\Db;

class Client extends BaseResource
{
    public function getList(array $restParams, $request)
    {
        $page = $request->getIn('pageNumber', 1);
        $pageSize = $request->getIn('pageSize', 10);

        $memberId = $request->getAttribute('member_id');
        $query = FDB::from('client')
            ->where('is_deleted', 0)
            ->where('reg_by_member', $memberId);
        $total = $query->count();

        $query = $query->offset($pageSize * ($page - 1))->limit($pageSize)->orderBy('created_at desc');
        $list = $query->fetchAll();

        $sexEnum = new Sex();
        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['sex_text'] = $sexEnum->getDescByNum($v['sex']);
            }
        }

        return ['total' => $total, 'rows' => $list];
    }

    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return mixed
     * @throws \Envms\FluentPDO\Exception
     */
    public function getInfo(array $restParams, $request)
    {
    }


    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @throws \Envms\FluentPDO\Exception
     */
    public function add(array $restParams, $request)
    {
        $params = $request->getParsedBody();

        $articleId = $request->getIn('article_id');

        $articleInfo = ArticleEntity::getByPk($articleId);
        $memberId = $articleInfo->memberId();

        $data = [
            'reg_by_member' => $memberId,
            'reg_by_article' => $articleId,
            'username' => $request->getIn('username', ''),
            'password' => $request->getIn('password', ''),
            'contact' => $request->getIn('contact', ''),
            'sex' => $request->getIn('sex', 0),
            'favor' => json_encode($params, JSON_UNESCAPED_UNICODE),
        ];

        $ret = ClientEntity::insert($data);

        return ResponseGen::success([$ret], "提交成功，请等待审核，审核成功会按您预留的联系方式通知您。");
    }


//    public function edit(array $restParams, $request)
//    {
//    }
//
//    public function delete(array $restParams, $request)
//    {
//    }
}
